package com.yq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yq.constant.AuthConstants;
import com.yq.domain.SysLoginUser;
import com.yq.mapper.SysLoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType)){
            return null;
        }
        switch (loginType){
            case AuthConstants.SYS_LOGIN_USER:
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username));
                if (!ObjectUtils.isEmpty(sysLoginUser)){
                    List<String> auths = sysLoginUserMapper.selectAuthById(sysLoginUser.getUserId());
                    sysLoginUser.setAuths(auths);
                }
                return sysLoginUser;
            case AuthConstants.MEMBER:
            default:
                return null;
        }
    }
}
